package com.ddwl.order.dao;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.Constant;
import com.ddwl.common.constant.OrderEnum;
import com.ddwl.common.dao.TkDao;
import com.ddwl.common.exception.GlobalException;
import com.ddwl.order.dao.mapper.OrderInfoMapper;
import com.ddwl.order.dao.model.OrderInfo;
import com.ddwl.order.dao.model.OrderSpu;
import com.ddwl.order.util.ExportOrderInfo;
import com.ddwl.schema.bo.order.OrderListApiBo;
import com.ddwl.schema.bo.order.OrderUpdateBo;
import com.ddwl.schema.bo.order.QueryOrderListBo;
import com.ddwl.schema.bo.order.QueryUserDistOrderBo;
import com.ddwl.schema.vo.order.ShopOrderCountVo;
import com.ddwl.schema.vo.order.StatisticsAmountVo;
import com.ddwl.schema.vo.order.UserOrderCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;

/**
 * (OrderInfo)表数据库访问层
 *
 * @author makejava
 * @since 2020-06-02 14:48:12
 */
@Slf4j
@Repository
public class OrderInfoDao extends TkDao<OrderInfoMapper, OrderInfo> {

    @Resource
    private OrderInfoMapper orderInfoMapper;


    /**
     * 查询订单列表包含商品信息
     * @return
     */
    public List<OrderInfo> queryOrderSpuList(QueryOrderListBo bo){
        List<OrderInfo> orderInfos=orderInfoMapper.queryOrderList(bo);
        for (OrderInfo orderInfo : orderInfos){
            orderInfo.setSpus(JSON.parseArray(orderInfo.getSkuSnapshoot(), OrderSpu.class));
        }
        return orderInfos;
    }

    /**
     * 查询订单金额:区分小程序,app,微信,支付宝
     * @return
     */
    public List<StatisticsAmountVo> queryOrderSpuListAmount(QueryOrderListBo bo){
        List<StatisticsAmountVo> statisticsAmountVos = orderInfoMapper.queryOrderAmount(bo);
        return statisticsAmountVos;
    }

    /**
     * 查询订单列表包含商品信息
     * @return
     */
    public Integer queryOrderCount(QueryOrderListBo bo){
        Integer count=orderInfoMapper.queryOrderCount(bo);
        return count;
    }

    /**
     * 查询订单导出详情
     * @return
     */
    public List<ExportOrderInfo> queryExportOrderList(QueryOrderListBo bo){
        List<ExportOrderInfo> exportOrderInfoVos = orderInfoMapper.queryExportOrderList(bo);
        return exportOrderInfoVos;
    }


    /**
     * 查询订单列表
     * @return
     */
    public List<OrderInfo> queryOrderSpuApiList(OrderListApiBo bo){
        Example example = getExample();
        example.and()
                .andEqualTo("status",bo.getStatus())
                .andNotEqualTo("status",0)
                .andEqualTo("id",bo.getOrderId())
                .andIn("supplierId",bo.getSupplierList());
        if (bo.getOrderByModify()!=null&&bo.getOrderByModify()){
            example.setOrderByClause("gmt_modified desc");
        }else {
            example.setOrderByClause("gmt_created desc");
        }
        return baseMapper.selectByExample(example);
    }

    /**
     * 查询订单数量金额列表
     * @return
     */
    public ShopOrderCountVo queryShopOrderList(QueryOrderListBo bo){
        return baseMapper.queryShopOrderList(bo);
    }

    /**
     * 查询订单数量金额列表
     * @return
     */
    public ShopOrderCountVo queryUnsendOrder(QueryOrderListBo bo){
        return baseMapper.queryUnsendOrder(bo);
    }

    /**
     * 查询用户分销的订单
     * @param bo
     * @return
     */
    public List<OrderInfo> queryDistOrder(QueryUserDistOrderBo bo){
        Example example = getExample();
        example.and().andEqualTo("status",bo.getStatus())
                .andIn("status", Arrays.asList(
                        OrderEnum.OrderStatus.PAYED.getCode(),
                        OrderEnum.OrderStatus.SEND.getCode(),
                        OrderEnum.OrderStatus.RECEIVED.getCode(),
                        OrderEnum.OrderStatus.REFUNDING.getCode(),
                        OrderEnum.OrderStatus.REFUND.getCode()))
                .andGreaterThanOrEqualTo("payTime",bo.getStartTime())
                .andLessThan("payTime",bo.getEndTime());
        example.and().orEqualTo("distUserId",bo.getUserId())
                .orEqualTo("regionUserId",bo.getUserId());
        List<OrderInfo> orderInfos = baseMapper.selectByExample(example);
        for (OrderInfo orderInfo : orderInfos){
            orderInfo.setSpus(JSON.parseArray(orderInfo.getSkuSnapshoot(), OrderSpu.class));
        }
        return orderInfos;
    }


    /**
     * 关闭订单
     * @param orderNo
     */
    public void orderClosed(String orderNo,String userId,String msg){
        OrderInfo orderInfo =  new OrderInfo();
        orderInfo.setStatus(OrderEnum.OrderStatus.CLOSE.getCode());
        orderInfo.setGmtModified(Instant.now());
        orderInfo.setCloseTime(Instant.now());
        orderInfo.setFinishTime(Instant.now());
        orderInfo.setCloseMsg(msg);
        Example example = new Example(OrderInfo.class);
        example.and().andEqualTo("id",orderNo)
                .andEqualTo("userId",userId)
                .andEqualTo("status", OrderEnum.OrderStatus.UN_PAY.getCode());
        Integer i =baseMapper.updateByExampleSelective(orderInfo,example);
        if(i<1){
            log.error("关闭订单失败 orderNo={}", JSON.toJSONString(orderNo));
            throw new GlobalException("关闭订单失败");
        }
    }

    /**
     * 更新订单备注
     * @param bo
     */
    public void updateRemark(OrderUpdateBo bo){
        OrderInfo orderInfo =  new OrderInfo();
        orderInfo.setGmtModified(Instant.now());
        orderInfo.setRemark(bo.getRemark());
        Example example = new Example(OrderInfo.class);
        example.and().andEqualTo("id",bo.getOrderId());
        Integer i =baseMapper.updateByExampleSelective(orderInfo,example);
        if(i<1){
            log.error("更新订单备注失败 orderNo={}", JSON.toJSONString(bo.getOrderId()));
            throw new GlobalException("更新订单备注失败");
        }
    }

    /**
     * 查询已经发货的商品
     * @param deliveryTime
     * @return
     */
    public List<OrderInfo> queryDeliveryOrder(Instant deliveryTime){
        Example example = getExample();
        example.and().andEqualTo("status", OrderEnum.OrderStatus.SEND.getCode())
                .andLessThan("deliveryTime",deliveryTime);
        return baseMapper.selectByExample(example);
    }

    public List<OrderInfo> queryZtOrder(Instant time) {
        Example example = getExample();
        example.and().andIn("status", Arrays.asList(OrderEnum.OrderStatus.SEND.getCode(), OrderEnum.OrderStatus.PAYED.getCode()))
                .andEqualTo("deliveryType", OrderEnum.DeliveryType.ZT.getCode())
                .andLessThan("payTime", time);
        return baseMapper.selectByExample(example);
    }

    public List<OrderInfo> queryLocalDeliveryReceive(Instant time) {
        Example example = getExample();
        example.and().andEqualTo("status", Arrays.asList(OrderEnum.OrderStatus.SEND.getCode()))
                .andEqualTo("deliveryType", OrderEnum.DeliveryType.WS.getCode())
                .andLessThan("deliveryTime", time);
        return baseMapper.selectByExample(example);
    }
    /**
     * 根据手机号查询订单
     * @param bo
     * @return
     */
    public List<OrderInfo> queryOrderByPhone(QueryOrderListBo bo) {
        List<OrderInfo> orderInfos=orderInfoMapper.queryOrderList(bo);
        for (OrderInfo orderInfo : orderInfos) {
            orderInfo.setSpus(JSON.parseArray(orderInfo.getSkuSnapshoot(), OrderSpu.class));
        }
        return orderInfos;
    }


    /**
     * 查询过期订单
     * @return
     */
    public List<OrderInfo> selectExpirationOrder(){
        Example example = getExample();
        example.and()
                .andLessThan("expirationTime",Instant.now())
                .andEqualTo("status", OrderEnum.OrderStatus.UN_PAY.getCode());
        return baseMapper.selectByExample(example);
    }

    /**
     * 关闭超时的订单
     */
    public void orderExpirationClosed(){
        OrderInfo orderInfo =  new OrderInfo();
        orderInfo.setStatus(OrderEnum.OrderStatus.CLOSE.getCode());
        orderInfo.setGmtModified(Instant.now());
        orderInfo.setCloseTime(Instant.now());
        orderInfo.setFinishTime(Instant.now());
        orderInfo.setCloseMsg(Constant.CLOSE_EXPIRATION_MSG);
        Example example = new Example(OrderInfo.class);
        example.and()
                .andLessThan("expirationTime",Instant.now())
                .andEqualTo("status", OrderEnum.OrderStatus.UN_PAY.getCode());
        baseMapper.updateByExampleSelective(orderInfo,example);
    }

    /**
     * 查询订单列表
     * @return
     */
    public List<OrderInfo> updateOrderList(List<String> list){
        Example example = getExample();
        example.and()
                .andIn("id",list)
        ;
        return baseMapper.selectByExample(example);
    }

    public UserOrderCountVo queryUserOrderCount(String userId) {
        return baseMapper.getUserOrderCount(userId);
    }

    public UserOrderCountVo queryWbmUserOrderCount(String shopId) {
        return baseMapper.getWbmUserOrderCount(shopId);
    }
}